import time
import math
import subprocess
import psutil
import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306
from PIL import Image, ImageDraw, ImageFont

# 配置树莓派引脚
RST = 24
# 一下配置，只在使用SPI接口时有用，使用I2C接口时可以忽略。
DC = 23
SPI_PORT = 0
SPI_DEVICE = 0

# 初始化 128x32 显示器 I2C
disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST)
disp.begin()
width = disp.width   # 128
height = disp.height # 32

def get_system_info():
    """获取系统信息"""
    info = []
    
    # 获取 WiFi SSID
    try:
        cmd = "iwgetid -r"
        ssid = subprocess.check_output(cmd, shell=True).decode('utf-8').strip()
        info.append(f"WiFi: {ssid}")
    except:
        info.append("WiFi: Not Connected")
    
    # 获取 IP 地址
    try:
        cmd = "hostname -I"
        ip = subprocess.check_output(cmd, shell=True).decode('utf-8').split()[0]
        info.append(f"IP: {ip}")
    except:
        info.append("IP: No IP Address")
    
    # CPU 使用率
    cpu_usage = psutil.cpu_percent()
    info.append(f"CPU: {cpu_usage:.1f}%")
    
    # 内存使用率
    memory = psutil.virtual_memory()
    info.append(f"RAM: {memory.percent:.1f}%")
    
    return info

def scroll_text(draw, image, text, direction="left"):
    """滚动显示文本"""
    font = ImageFont.load_default()
    text_width = draw.textlength(text, font=font)
    text_height = 8  # 默认字体高度
    
    y_position = (height - text_height) // 2
    
    if direction == "left":
        # 从右向左滚动
        for x_pos in range(width, -text_width-10, -4):
            draw.rectangle((0, 0, width, height), outline=0, fill=0)
            draw.text((x_pos, y_position), text, font=font, fill=255)
            disp.image(image)
            disp.display()
            time.sleep(0.01)
    else:
        # 从左向右滚动
        for x_pos in range(-text_width-10, width, 4):
            draw.rectangle((0, 0, width, height), outline=0, fill=0)
            draw.text((x_pos, y_position), text, font=font, fill=255)
            disp.image(image)
            disp.display()
            time.sleep(0.01)

def main():
    # 创建图像缓冲
    image = Image.new('1', (width, height))
    draw = ImageDraw.Draw(image)
    
    try:
        while True:
            # 获取系统信息
            info_list = get_system_info()
            
            # 循环显示每条信息
            for i, info in enumerate(info_list):
                # 显示当前信息
                scroll_text(draw, image, info, "left")
                time.sleep(3)  # 显示3秒
                
                # 滚出当前信息
                scroll_text(draw, image, info, "right")
                
    except KeyboardInterrupt:
        # 清空显示
        disp.clear()
        # 手工清除图像
        draw.rectangle((0,0,128,64),outline=0,fill=0)
        disp.display()

if __name__ == "__main__":
    main() 